
import com.bm.config.server.IServerServices;
import com.bm.setting.ServerConfig;
import com.bm.util.*;
import java.sql.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Mirza at Bimasakti
 */
public class MI_SMS {

    private static int limitRow;

    public static String initServer(String clientID) {
        int state = 0;
        Connection c = null;
        try {
            ConfigReader konfigurasi = new ConfigReader();
            state++;
            limitRow = konfigurasi.getLimitRow();
            state++;
            ServerConfig sc = new ServerConfig(new IServerServices());
            state++;
            c = ServerConfig.getConnection();
            state++;
        } catch (Exception e) {
            return "Error init Server at " + state + ": " + e.getMessage();
        } finally {
            ServerConfig.close(c);
            state++;
        }
        return "Success init all state ";
    }

    public static boolean echoTest() {
        return true;
    }

    public static Object getDateCreatedFile(String messageId) {
        int step = 0;
        MessagePrinter.printLog("Message ID", messageId);
        Connection conn = ServerConfig.getConnection();
        ResultSet rs = null;
        PreparedStatement ps = null;
        Timestamp d = null;
        try {
            // get date created message            
            String qry = "SELECT date_created FROM "
                    + ServerConfig.getDBName()
                    + ".message_outbox WHERE id_message=? ";
            ps = conn.prepareStatement(qry);
            step++;
            ps.setInt(1, Integer.valueOf(messageId)); // 1 success prepare statement
            rs = ps.executeQuery();
            step++; // 2 success execute query
            if (rs.next()) {
                d = rs.getTimestamp("date_created");
                step++; // 3 success retrieve date
            }
        } catch (SQLException ex) {
            MessagePrinter.printLog("Error SQL", ex.getMessage());
            Logger.getLogger(MI_SMS.class.getName()).log(Level.SEVERE, null, ex);
            return "Last step " + step + " with message :" + ex.getMessage();
        } finally {
            ServerConfig.close(ps);
            ServerConfig.close(rs);
            ServerConfig.close(conn);
            if (d != null) {
                return d;
            } else {
                return "Last step " + step;
            }
        }
    }

    public static void updateMessageOutbox(int id_message, String status, String id_modul) throws SQLException {
        MessagePrinter.printDebung("1. [" + id_message + "] update outbox status: " + status);
        String qry = "UPDATE " + ServerConfig.getDBName() + ".message_outbox SET is_sent = " + status + " WHERE id_message=?";
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = ServerConfig.getConnection();
            ps = conn.prepareStatement(qry);
            ps.setInt(1, id_message);
            ps.executeUpdate();
            MessagePrinter.printDebung("2. [" + id_message + "] update outbox successfull");
        } catch (SQLException ex) {
        } finally {
            ServerConfig.close(ps);
            ServerConfig.close(conn);
        }
    }

    public static Object selectFromMessageOutbox(String dummy, String id_modul) {
        int step = 0;
        step++; // init connection
        String qry = "SELECT id_message, receiver, content, id_modul FROM "
                + ServerConfig.getDBName()
                + ".message_outbox WHERE is_sent = 0 "
//                + ".message_outbox WHERE is_sent = 0 and id_modul " + (id_modul.equals("") ? "IS NULL" : "= '" + id_modul + "'") + " "
                + "order by date_created asc limit " + limitRow;        
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        MrResultSetAdapter mrRSAdapter = null;
        try {
            conn = ServerConfig.getConnection();
            stmt = conn.createStatement();
            rs = stmt.executeQuery(qry);
            step++; // execute query
            mrRSAdapter = new MrResultSetAdapter(rs);
            step++; // convert to MRResultAdapter
        } catch (SQLException ex) {
            Logger.getLogger(MI_SMS.class.getName()).log(Level.SEVERE, null, ex);
            return "Last step " + step + " with message " + ex.getMessage();
        } finally {
            ServerConfig.close(rs);
            ServerConfig.close(stmt);
            ServerConfig.close(conn);
        }
        return mrRSAdapter;
    }

    public static boolean insertIntoInbox(int step, String sender, String receiver, String content, String id_modul, String via, int is_sent, String sentDate) throws SQLException {
        String qry;
        
        int mid = 1;
        qry = "INSERT INTO "
                + ServerConfig.getDBName()
                + ".message_inbox(mid, step, sender, receiver, content, id_modul, via, is_sent, date_created, sent_date) "
                + "values(?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?)";
        Connection conn2 = null;
        PreparedStatement ps = null;
        try {
            conn2 = ServerConfig.getConnection();
            ps = conn2.prepareStatement(qry);
            ps.setInt(1, mid);
            ps.setInt(2, step);
            ps.setString(3, sender);
            ps.setString(4, receiver);
            ps.setString(5, content);
            ps.setString(6, id_modul);
            ps.setString(7, via);
            ps.setInt(8, is_sent);

            DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            java.sql.Timestamp da = new java.sql.Timestamp(df2.parse(sentDate).getTime());
            ps.setTimestamp(9, da);
            ps.executeUpdate();
            
            return true;
        } catch (ParseException ex) {
            System.out.println(ex.getMessage());
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        } finally {
            ServerConfig.close(ps);
            ServerConfig.close(conn2);
        }
        return false;
    }
}
